package com.yss.reportworld.controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.yss.common.core.constant.Constants;
import com.yss.common.core.utils.easyexecl.EasyExeclUtil;
import com.yss.reportworld.service.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yss.common.logger.annotation.Log;
import com.yss.common.logger.enums.BusinessType;
import com.yss.common.security.annotation.RequiresPermissions;
import com.yss.reportworld.domain.Database;
import com.yss.common.core.web.controller.BaseController;
import com.yss.common.core.web.domain.AjaxResult;

/**
 * 基础数据Controller
 *
 * @author yss
 * @date 2023-03-29
 */
@RestController
@RequestMapping("/database")
public class DatabaseController extends BaseController {
    @Autowired
    private IDatabaseService databaseService;
    @Autowired
    private IModularService modularService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IReportService reportService;
    @Autowired
    private IUpgradeToolsZipService upgradeToolsZipService;
    @Autowired
    private IDescriptionService descriptionService;
    @Autowired
    private ISqlScriptService sqlScriptService;

    /**
     * 查询基础数据列表
     */
    @RequiresPermissions("reportworld:database:list")
    @GetMapping("/list")
    public AjaxResult list(Database database) {
        List<Database> list = databaseService.selectDatabaseList(database);
        return success(list);
    }

    /**
     * 初始化 加载
     */
    @RequiresPermissions("reportworld:database:list")
    @Log(title = "基础数据", businessType = BusinessType.OTHER)
    @PostMapping("/init")
    public AjaxResult init(@RequestBody Database database) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("reductionVersions", sqlScriptService.getReductionVersion(false));
        ajax.put("checkVersions", sqlScriptService.getReductionVersion(true));
        return ajax;
    }

    /**
     * 导出基础数据列表
     */
    @RequiresPermissions("reportworld:database:export")
    @Log(title = "基础数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Database database) {
        List<Database> list = databaseService.selectDatabaseList(database);
        EasyExeclUtil.export(response, list, Database.class);
    }

    /**
     * 获取基础数据详细信息
     */
    @RequiresPermissions("reportworld:database:query")
    @PostMapping(value = "/getDatabase")
    public AjaxResult getDatabase(@RequestBody Database database) {
        return success(databaseService.getDatabaseById(database));
    }


    @RequiresPermissions("reportworld:database:query")
    @PostMapping(value = "/getDatabaseByCode")
    public AjaxResult getDatabaseByCode(@RequestBody Database database) {
        return success(databaseService.queryDatabaseOne(database));
    }

    /**
     * 新增基础数据
     */
    @RequiresPermissions("reportworld:database:add")
    @Log(title = "基础数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated Database database) {
        databaseService.addDataBase(database);
        return success();
    }

    /**
     * 修改基础数据
     */
    @RequiresPermissions("reportworld:database:edit")
    @Log(title = "基础数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated Database database) {
        databaseService.editDataBase(database);
        return success();
    }

    /**
     * 删除基础数据
     */
    @RequiresPermissions("reportworld:database:remove")
    @Log(title = "基础数据", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody Database database) {
        databaseService.delDataBase(database);
        return success();
    }

    /***
     * 构建基础数据信息，可以生成表和需要得配置信息，包括备份和升级策略信息
     * @param database
     * @return
     */
    @RequiresPermissions("reportworld:database:data:structure")
    @PostMapping(value = "/structureDataBase")
    public AjaxResult structureDataBase(@RequestBody Database database) {
        AjaxResult ajax = AjaxResult.success();
        databaseService.structureDataBase(database);
        return ajax;
    }

    /**
     * 导出zip文件，提供给升级工具
     *
     * @return
     * @throws Exception
     */
    @RequiresPermissions("reportworld:upgradetoolszip")
    @Log(title = "基础数据", businessType = BusinessType.EXPORT)
    @PostMapping(value = "/downUpgradeToolsZip")
    public void downUpgradeToolsZip(HttpServletResponse response, Database database) throws Exception {
        byte[] data = upgradeToolsZipService.downUpgradeToolsZip(database);
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /***
     * 查询基础信息数据列表
     * @param queryJson
     * @return
     */
    @RequiresPermissions("reportworld:database:data:list")
    @PostMapping(value = "/getDataBaseInfo")
    public AjaxResult getDataBaseInfo(@RequestBody String queryJson) {
        AjaxResult ajax = AjaxResult.success();
        //加载所属模块，客户，报表
        ajax.put("modularTree", modularService.selectModularTreeList());
        ajax.put("customerTree", customerService.selectCustomerTreeList());
        ajax.put("reportTree", reportService.selectReportTreeList());
        ajax.put("formList", databaseService.getDataBaseTableInfo(queryJson));
        ajax.put("hisVersions", sqlScriptService.getReductionVersion(false));
        ajax.putAll(databaseService.queryDataBaseByCode(queryJson));
        return ajax;
    }

    /***
     * 新增基础信息数据列表
     * @param addJson
     * @return
     */
    @RequiresPermissions("reportworld:database:data:add")
    @PostMapping(value = "/addDataBaseInfo")
    public AjaxResult addDataBaseInfo(@RequestBody String addJson) {
        AjaxResult ajax = AjaxResult.success();
        databaseService.addDataBaseInfo(addJson);
        return ajax;
    }

    /***
     * 修改基础信息数据列表
     * @param updateJson
     * @return
     */
    @RequiresPermissions("reportworld:database:data:edit")
    @PostMapping(value = "/updateDataBaseInfo")
    public AjaxResult updateDataBaseInfo(@RequestBody String updateJson) {
        AjaxResult ajax = AjaxResult.success();
        databaseService.updateDataBaseInfo(updateJson);
        return ajax;
    }

    /***
     * 删除基础信息数据列表
     * @param deleteJson
     * @return
     */
    @RequiresPermissions("reportworld:database:data:remove")
    @PostMapping(value = "/removeDataBaseInfo")
    public AjaxResult removeDataBaseInfo(@RequestBody String deleteJson) {
        AjaxResult ajax = AjaxResult.success();
        databaseService.deleteDataBaseInfo(deleteJson);
        return ajax;
    }

    /***
     * 修改基础信息数据列表
     * @param updateJson
     * @return
     */
    @RequiresPermissions("reportworld:database:data:batchEdit")
    @PostMapping(value = "/handleUpdateBatch")
    public AjaxResult handleUpdateBatch(@RequestBody String updateJson) {
        AjaxResult ajax = AjaxResult.success();
        databaseService.handleUpdateBatch(updateJson);
        return ajax;
    }

    /**
     * 基础数据Execl导出
     */
    @RequiresPermissions("reportworld:database:data:execl")
    @Log(title = "基础数据", businessType = BusinessType.EXPORT)
    @PostMapping("/exportData")
    public void exportData(HttpServletResponse response, String queryJson) {
        List<Map<String, Object>> list = databaseService.dataBaseExecl(queryJson);
        EasyExeclUtil.excelExportNew(list, response);
    }

    /**
     * 导出插入语句
     */
    @RequiresPermissions("reportworld:database:data:sql")
    @Log(title = "基础数据", businessType = BusinessType.EXPORT)
    @PostMapping("/dataBaseSql")
    public void dataBaseSql(HttpServletResponse response, String queryJson) throws IOException {
        String sql = databaseService.dataBaseSql(queryJson);
        IOUtils.write(sql, response.getOutputStream(), Constants.UTF8);
    }

    /**
     * 查看一个表的策略信息
     *
     * @param code
     * @return
     */
    @RequiresPermissions("reportworld:database:compareconfig")
    @GetMapping(value = "/getCompareconfig/{code}")
    public AjaxResult getCompareconfig(@PathVariable("code") String code) {
        return success(descriptionService.getCompareconfig(code));
    }


    /***
     * 修改一个表的策略信息
     * @param updateJson
     * @return
     */
    @RequiresPermissions("reportworld:database:compareconfig:edit")
    @PostMapping(value = "/updateCompareconfig")
    public AjaxResult updateCompareconfig(@RequestBody String updateJson) {
        AjaxResult ajax = AjaxResult.success();
        descriptionService.updateCompareconfig(updateJson);
        return ajax;
    }
}
